#!/bin/bash
#
# HDCON	Start up the HDCON server daemon
#
# chkconfig: 2345 80 25
# description: HDCON video conference server
#
# processname: hdcon
# config: /etc/hdcon/daemon.conf
# pidfile: /var/run/hdcon/hdcon.pid

### BEGIN INIT INFO
# Provides:          hdcon
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: HDCON
# Description:       HDCON video conference server
### END INIT INFO

DAEMON_DESC="HDCON video conference server"
DAEMON_NAME="hdcon"
DAEMON_DIR="/opt/$DAEMON_NAME"
DAEMON_EXEC="$DAEMON_DIR/bin/hdcon"
DAEMON_PIDDIR="/var/run/$DAEMON_NAME"
DAEMON_PIDFILE="$DAEMON_PIDDIR/$DAEMON_NAME.pid"
SCRIPTNAME="/etc/rc.d/init.d/$DAEMON_NAME"

# Exit if the package is not installed
[ -x "$DAEMON_EXEC" ] || exit 0

# Read configuration variable file if it is present
DAEMON_ENABLED=true
DAEMON_USER="mcu"
DAEMON_COREDUMP="0"
DAEMON_CONF="$DAEMON_DIR/config/daemon.conf"
if [ -r "$DAEMON_CONF" ] ; then
  . "$DAEMON_CONF"
fi

if ! $DAEMON_ENABLED ; then
  echo "Daemon $DAEMON_NAME disabled ($DAEMON_CONF)" >&2
  exit 0
fi

# source function library
. /etc/rc.d/init.d/functions

#
# Function that starts the daemon/service
#
do_start()
{

  if [ ! -d "$DAEMON_PIDDIR" ] ; then
    mkdir "$DAEMON_PIDDIR"
  fi
  chown -R "$DAEMON_USER": "$DAEMON_PIDDIR"

  export LD_LIBRARY_PATH="$DAEMON_DIR/lib"
  if [ ! -z "$DAEMON_MAXPROCESSES" ] ; then
    ulimit -u $DAEMON_MAXPROCESSES
  fi
  if [ ! -z "$DAEMON_MAXOPENFILES" ] ; then
    ulimit -n $DAEMON_MAXOPENFILES
  fi

  if do_status >/dev/null 2>&1 ; then
    echo "Service $DAEMON_NAME is already running."
    return 0
  fi
  echo -n $"Starting $DAEMON_NAME: "
  DAEMON_COREFILE_LIMIT=$DAEMON_COREDUMP
  daemon --user=$DAEMON_USER $DAEMON_EXEC --daemon --pid-file $DAEMON_PIDFILE >/dev/null 2>&1 && success || failure
  RETVAL=$?
  echo
  return $RETVAL
}

#
# Function that stops the daemon/service
#
do_stop()
{

  echo -n $"Stopping $DAEMON_NAME: "
  killproc -p $DAEMON_PIDFILE $DAEMON_EXEC && success || failure
  RETVAL=$?
  [ "$RETVAL" = 0 ] && sleep 1s
  rm -f $DAEMON_PIDFILE
  echo
  return "$RETVAL"

}

#
# Function that shows status
#
do_status()
{
  status -p $DAEMON_PIDFILE $DAEMON_NAME
  return $?
}

case "$1" in

  start)
    do_start
  ;;

  stop)
    do_stop
  ;;

  status)
    do_status
  ;;

  restart)
    do_stop
    do_start
  ;;

  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
    exit 3
  ;;
  
esac

exit $?
